package com.example.keepserver.init;

import com.example.keepserver.model.Activity;
import com.example.keepserver.model.User;
import com.example.keepserver.repository.ActivityRepository;
import com.example.keepserver.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Component
public class DataInitializer implements CommandLineRunner {

    private final UserRepository userRepository;
    private final ActivityRepository activityRepository;
    private final Random random = new Random();
    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Autowired
    public DataInitializer(UserRepository userRepository, ActivityRepository activityRepository) {
        this.userRepository = userRepository;
        this.activityRepository = activityRepository;
    }

    @Override
    public void run(String... args) throws Exception {
        // 检查用户数据是否已经存在
        if (userRepository.count() == 0) {
            System.out.println("初始化示例用户数据...");
            initializeUsers();
        }

        // 检查活动数据是否已经存在
        if (activityRepository.count() == 0) {
            System.out.println("初始化示例活动数据...");
            initializeActivities();
        }
    }

    private void initializeUsers() {
        List<User> users = new ArrayList<>();

        // 创建5个用户
        users.add(createUser("user001", "跑步达人", "男", "北京", 320, 86));
        users.add(createUser("user002", "骑行一族", "男", "上海", 245, 42));
        users.add(createUser("user003", "游泳健将", "女", "广州", 178, 35));
        users.add(createUser("user004", "健身狂人", "男", "深圳", 412, 120));
        users.add(createUser("user005", "瑜伽爱好者", "女", "杭州", 289, 75));

        userRepository.saveAll(users);
    }

    private User createUser(String userId, String nickname, String gender, String location, int followers, int following) {
        User user = new User();
        user.setUserId(userId);
        user.setNickname(nickname);
        user.setAvatarUrl("https://placekitten.com/100/100?id=" + userId);
        user.setGender(gender);
        user.setLocation(location);
        user.setFollowerCount(followers);
        user.setFollowingCount(following);
        user.setPostCount(random.nextInt(200) + 50);
        user.setCreatedAt(LocalDateTime.now().minusDays(random.nextInt(365) + 30));
        return user;
    }

    private void initializeActivities() {
        List<Activity> activities = new ArrayList<>();
        List<User> users = userRepository.findAll();
        if (users.isEmpty()) {
            System.out.println("没有用户数据，无法创建活动");
            return;
        }

        String[] activityTypes = {"跑步", "骑行", "游泳", "健身", "瑜伽", "徒步", "舞蹈"};
        String[] locations = {"城市公园", "健身房", "游泳馆", "郊外", "小区", "山地", "海滩"};
        String[] weatherConditions = {"晴天", "多云", "小雨", "室内", "大风", "雾天"};

        // 为每个用户创建一些活动
        int activityId = 1;
        for (User user : users) {
            // 每个用户10-30个活动
            int activityCount = 10 + random.nextInt(20);
            
            for (int i = 0; i < activityCount; i++) {
                String type = activityTypes[random.nextInt(activityTypes.length)];
                
                LocalDateTime startTime = LocalDateTime.now().minusDays(random.nextInt(60))
                        .minusHours(random.nextInt(24))
                        .minusMinutes(random.nextInt(60));
                
                // 根据活动类型设置不同的距离和时长
                float distance = 0;
                int duration = 0;
                float calorie = 0;
                
                if (type.equals("跑步")) {
                    distance = 2 + random.nextFloat() * 10; // 2-12km
                    duration = (int) (distance * (300 + random.nextInt(100))); // 约5-7分钟/公里
                    calorie = distance * (60 + random.nextFloat() * 20); // 约60-80卡/公里
                } else if (type.equals("骑行")) {
                    distance = 5 + random.nextFloat() * 35; // 5-40km
                    duration = (int) (distance * (120 + random.nextInt(60))); // 约2-3分钟/公里
                    calorie = distance * (30 + random.nextFloat() * 10); // 约30-40卡/公里
                } else if (type.equals("游泳")) {
                    distance = 0.5f + random.nextFloat() * 2.5f; // 0.5-3km
                    duration = (int) (distance * (1200 + random.nextInt(600))); // 约20-30分钟/公里
                    calorie = distance * (300 + random.nextFloat() * 100); // 约300-400卡/公里
                } else if (type.equals("健身") || type.equals("瑜伽")) {
                    distance = 0;
                    duration = 1800 + random.nextInt(5400); // 30-120分钟
                    calorie = duration / 60 * (5 + random.nextFloat() * 5); // 约5-10卡/分钟
                } else if (type.equals("徒步")) {
                    distance = 3 + random.nextFloat() * 12; // 3-15km
                    duration = (int) (distance * (600 + random.nextInt(300))); // 约10-15分钟/公里
                    calorie = distance * (50 + random.nextFloat() * 20); // 约50-70卡/公里
                } else {
                    distance = 0;
                    duration = 1800 + random.nextInt(3600); // 30-90分钟
                    calorie = duration / 60 * (4 + random.nextFloat() * 4); // 约4-8卡/分钟
                }
                
                Activity activity = new Activity();
                activity.setActivityId("a" + String.format("%06d", activityId++));
                activity.setUser(user);
                activity.setType(type);
                activity.setTitle(type + " - " + formatDate(startTime));
                activity.setDescription(user.getNickname() + "的" + type + "记录");
                activity.setDistance(distance);
                activity.setDuration(duration);
                activity.setCalorie(calorie);
                activity.setStartTime(startTime);
                activity.setLikesCount(random.nextInt(50));
                activity.setCommentsCount(random.nextInt(20));
                activity.setCreatedAt(startTime);

                activities.add(activity);
            }
        }

        activityRepository.saveAll(activities);
        System.out.println("已创建 " + activities.size() + " 条活动记录");
    }
    
    private String formatDate(LocalDateTime dateTime) {
        return dateTime.format(formatter);
    }
} 